package com.fg.cloud.factory.controller.product;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.fg.cloud.common.PageUtils;
import com.fg.cloud.common.Result;
import com.fg.cloud.common.ServiceException;
import com.fg.cloud.common.StatusCode;
import com.fg.cloud.common.quantity.ResultType;
import com.fg.cloud.framework.controller.BaseController;
import com.fg.cloud.manager.entry.product.ProductInfoEntity;
import com.fg.cloud.manager.entry.product.ProductParamEntity;
import com.fg.cloud.manager.entry.product.ProductSkuEntity;
import com.fg.cloud.manager.entry.product.vo.ProductInfoVo;
import com.fg.cloud.manager.entry.product.vo.ProductMoreUnitVo;
import com.fg.cloud.manager.service.product.ProductInfoService;
import com.fg.cloud.manager.service.product.ProductMoreUnitService;
import com.fg.cloud.manager.service.product.ProductParamService;
import com.fg.cloud.manager.service.product.ProductSkuImgService;
import com.fg.cloud.manager.service.product.ProductSkuService;

@Controller
@RequestMapping(value="/product")
public class ProductInfoController extends BaseController{
	@Autowired
	private ProductInfoService productService ; 
	@Autowired
	private ProductSkuService skuService ; 
	@Autowired
	private ProductSkuImgService imgService ;
	@Autowired
	private ProductParamService paramService ;
	@Autowired
	private ProductMoreUnitService pro_moreUnitService;
	
	/**
	  * Description:新增商品信息
	  * @param product 商品信息实体
	  * @author liushengchao
	  * @date 2017年7月31日下午3:55:12
	 */
	@RequestMapping(value="/insert",method={RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public void insert(HttpServletRequest req , HttpServletResponse resp , String productInfo){
		try {
			Long facId = getCurrentFactoryUser().getFacId();
			productInfo = StringEscapeUtils.unescapeHtml4(productInfo);
			ProductInfoEntity entity = JSON.parseObject(productInfo, ProductInfoEntity.class,Feature.OrderedField);
			Result result = productService.addProduct(entity, facId); 
			doResult(resp, result.isSuccess(), result.getCode(), result.getData(), result.getMessage());
		} catch (ServiceException e) {
			doResult(resp, false, e.getCode(), null, e.getMessage());
		}
	}
	
	/**
	  * Description:搜索框查询商品信息
	  * @param condition 搜索框输入的查询条件
	  * @param isGround 上架状态（经销商段默认此条件值为1，厂商段为0）
	  * @author liushengchao
	  * @date 2017年8月2日下午3:47:33
	 */
	@RequestMapping(value="/productlist",method={RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public void productList(HttpServletRequest req , HttpServletResponse resp,
			@Param("condition")String condition,@Param("isGround")Integer isGround,
			ProductSkuEntity skuInfo,
			Integer page, Integer rows, String sort, String order){
		ArrayList<String> conditionArr = new ArrayList<String>();
		if(!StringUtils.isEmpty(condition)){
			String[] arr = condition.split(" ");
			for(String arrStr : arr){
				conditionArr.add(arrStr);
			}
		}
		PageUtils<ProductSkuEntity> pageinfo = new PageUtils<ProductSkuEntity>(page, rows, sort, order);
		Map<String,Object> conditions = new HashMap<>();
		if(skuInfo.getCategoryId()!= null){
			conditions.put("categoryId", skuInfo.getCategoryId());
		}
		if(skuInfo.getCategoryId() != null ){
			conditions.put("categoryId", skuInfo.getCategoryId());	
		}
		if(skuInfo.getCategoryNumber() != null ){
			String categoryNumber = "" ;
			String number = skuInfo.getCategoryNumber() ;
			if("".equals(number)){
				categoryNumber = "0";
			}else{
				String numberRep = skuInfo.getCategoryNumber().replace(",", "_") ;
				categoryNumber = "0_"+numberRep ;
			}
			conditions.put("categoryNumber", categoryNumber);
		}
		if(!"".equals(skuInfo.getProductName() )){
			conditions.put("productName", skuInfo.getProductName());
		}
		if(!"".equals(skuInfo.getProductNumber() )){
			conditions.put("productNumber", skuInfo.getProductNumber());
		}
		if(!"".equals(skuInfo.getProductSpec())){
			conditions.put("productSpec", skuInfo.getProductSpec());
		}
		if(skuInfo.getIsGround() != null ){
			pageinfo.setIsGround(skuInfo.getIsGround());
		}
		pageinfo.setSelectCondition(conditionArr);
		pageinfo.setIsGround(isGround);
		pageinfo.setCondition(conditions);
		pageinfo.setFacId(getCurrentFactoryUser().getFacId());
		long total = productService.countTop(pageinfo);
		if(total == 0 ){
			doResult(resp, true, StatusCode.FINDSUCCESS, null, ResultType.FIND_SUCCESS);//"无对应数据，请确认查询条件");
			return ;
		}
		List<ProductSkuEntity> productList = productService.selectByCondition(pageinfo);
		pageinfo.setData(productList);
		pageinfo.setTotal(total);
		doResult(resp, true, StatusCode.FINDSUCCESS, pageinfo, "查询成功");
	}
	
	/**
	  * Description:高级搜索
	  * @param skuInfo 搜索信息参数集合
	  * @param page
	  * @param rows
	  * @param sort
	  * @param order
	  * @author liushengchao
	  * @date 2017年8月3日下午2:22:05
	 */
	@RequestMapping(value="/advsearch",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public void advSearch(HttpServletRequest req , HttpServletResponse resp,
			ProductSkuEntity skuInfo,Integer page, Integer rows, String sort, String order){
		PageUtils<ProductSkuEntity> pageinfo = new PageUtils<ProductSkuEntity>(page, rows, sort, order);
		try{
			Map<String,Object> condition = new HashMap<>();
			if(skuInfo.getCategoryId() != null ){
				condition.put("categoryId", skuInfo.getCategoryId());	
			}
			if(skuInfo.getCategoryNumber() != null ){
				String categoryNumber = "" ;
				String number = skuInfo.getCategoryNumber() ;
				if("".equals(number)){
					categoryNumber = "0";
				}else{
					String numberRep = skuInfo.getCategoryNumber().replace(",", "_") ;
					categoryNumber = "0_"+numberRep ;
				}
				condition.put("categoryNumber", categoryNumber);
			}
			if(!"".equals(skuInfo.getProductName() )){
				condition.put("productName", skuInfo.getProductName());
			}
			if(!"".equals(skuInfo.getProductNumber() )){
				condition.put("productNumber", skuInfo.getProductNumber());
			}
			if(!"".equals(skuInfo.getProductSpec())){
				condition.put("productSpec", skuInfo.getProductSpec());
			}
			if(skuInfo.getIsGround() != null ){
				pageinfo.setIsGround(skuInfo.getIsGround());
			}
			pageinfo.setCondition(condition);
			pageinfo.setFacId(getCurrentFactoryUser().getFacId());
			Long total = productService.count(pageinfo);
			if(total == 0 ){
				pageinfo.setData(new ArrayList<ProductSkuEntity>());
				pageinfo.setTotal(total);
				doResult(resp, true, StatusCode.NORETRUNDATA, pageinfo, "无对应数据，请确认查询条件");
				return ;
			}
			List<ProductSkuEntity> productList = productService.advSearch(pageinfo);
			pageinfo.setData(productList);
			pageinfo.setTotal(total);
			doResult(resp, true, StatusCode.FINDSUCCESS, pageinfo, ResultType.FIND_SUCCESS);
		}catch(Exception e){
			e.printStackTrace();
			doResult(resp, false, StatusCode.EXCEPTIONERROR, null, ResultType.FIND_FAULT);
		}
		
	}
	
	/**
	  * Description:商品信息修改
	  * @param req
	  * @param resp
	  * @param product 商品信息
	  * @author liushengchao
	  * @date 2017年8月3日下午6:30:31
	 */
	@RequestMapping(value="/modify",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public void modify(HttpServletRequest req , HttpServletResponse resp,
			String product, String skuListStr, String paramListStr){
		try{
			Long facId = getCurrentFactoryUser().getFacId();
			product = StringEscapeUtils.unescapeHtml4(product);
			ProductInfoEntity entity = JSON.parseObject(product, ProductInfoEntity.class);
			Result result = productService.modifyProduct(entity, facId);
			doResult(resp, result.isSuccess(), result.getCode(),result.getData(),result.getMessage());
		}catch(ServiceException e){
			doResult(resp, false, e.getCode(),null,e.getMessage());
		}
		
	}
	
	/**
	  * Description:查询商品详情
	  * @param req
	  * @param resp
	  * @param productId 商品ID
	  * @author liushengchao
	  * @date 2017年8月4日上午11:17:52
	 */
	@RequestMapping(value="/detail",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public void productDetail(HttpServletRequest req , HttpServletResponse resp,Long id,Long skuId){
		if(null == id){
			doResult(resp, false, StatusCode.LACKVALUE, null, "缺少商品ID");
			return ;
		}
		if(null == skuId){
			doResult(resp, false, StatusCode.LACKVALUE, null, "缺少商品ID");
			return ;
		}
		ProductInfoEntity product = productService.find(id);
		if(product == null || StringUtils.isEmpty(product.getProductName())){
			doResult(resp, false, StatusCode.NORETRUNDATA, null, "查询结果为空");
			return ;
		}
		List<ProductSkuEntity> skuList = new ArrayList<>() ;
		ProductSkuEntity sku = skuService.find(skuId);
		List<ProductMoreUnitVo> moreUnitList;
		StringBuffer moreUnitStr = new StringBuffer();
//		List<ProductSkuEntity> skuList = skuService.selectByProId(id);
		if(sku == null ){
			doResult(resp, false, StatusCode.NORETRUNDATA, null, "查询结果为空");
			return ;
		}
		if(1 == sku.getMultiUnit()) {
			moreUnitList = pro_moreUnitService.findList(null, skuId);
			moreUnitStr.append(sku.getUnitName()).append("/");
			for (int i = 0; i < moreUnitList.size(); i++)
				moreUnitStr.append(moreUnitList.get(i).getLongName()).append("/");
				
			sku.setMoreUnitList(moreUnitList);
			moreUnitStr.deleteCharAt(moreUnitStr.lastIndexOf("/"));
			sku.setMoreUnitContent(moreUnitStr.toString());
			moreUnitStr.setLength(0);
		}
		//追加规格处理
		sku.setProductSpec(splitSpec(sku.getProductSpec()));
		skuList.add(sku);
		List<ProductParamEntity> paramList = paramService.selectByProductId(id);
		List<String> imgList  ;
		
		imgList = imgService.selectByProductId(id);
		product.setImgList(imgList);
		product.setSkuList(skuList);
		product.setParamList(paramList);
		doResult(resp, true, StatusCode.FINDSUCCESS, product, "查询信息成功");
	}
	
	/**
	  * Description:删除商品信息
	  * @param req
	  * @param resp
	  * @param productId 商品ID
	  * @param skuIds 商品SKUID列表
	  * @author liushengchao
	  * @date 2017年8月7日下午5:05:09
	 */
	@RequestMapping(value="/delete",method={RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public void productDelete(HttpServletRequest req , HttpServletResponse resp,Long productId,Long skuId,boolean isDelProduct){
		Result result =  productService.deleteProduct(productId, skuId, isDelProduct);
		doResult(resp, result.isSuccess(), result.getCode(), result.getData(), result.getMessage());
	}
	
//	/**
//	  * Description:删除SKU对应的商品图册
//	  * @param skuId 
//	  * @return
//	  * @author liushengchao
//	  * @date 2017年8月7日下午6:08:25
//	 */
//	public boolean deleteSkuPic(Long skuId){
//		boolean result = false ;
//		try {
//			List<ProductSkuImgEntity> imgList = imgService.selectBySkuId(skuId);
//			if(imgList != null && imgList.size() > 0){
//				for(ProductSkuImgEntity img : imgList){
//					result = imgService.deleteFile(img.getUrl());
//				}
//				return result ;
//			}else{
//				result = true ;
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return result ;
//	}
//	
	/**
	  * Description:判断商品详情的必填字段
	  * @param skuList 商品详情列表
	  * @return
	  * @author liushengchao
	  * @date 2017年8月16日下午6:20:31
	 */
	public boolean judgeSku(List<ProductSkuEntity> skuList ){
		if(skuList != null && skuList.size() > 0){
			for(ProductSkuEntity skuInfo : skuList){
				if(StringUtils.isEmpty(skuInfo.getProductName()) || StringUtils.isEmpty(skuInfo.getProductNumber())
						|| skuInfo.getProductUnit() < 0 || skuInfo.getProductPrice() == null ||skuInfo.getProductPrice().compareTo(new BigDecimal(0))==-1)
				{
					return false;
				}
				return true ;
			}
		}
		return false;
	}
	@RequestMapping(value="/batchdelete")
	public void batchDelete(HttpServletRequest  req,HttpServletResponse resp,@Param("ids")String ids){
		if(StringUtils.isEmpty(ids)){
			doResult(resp, false, StatusCode.LACKVALUE, null, "传入ID为空");
		}
//		List<Object> idList =  JSONObject.parseArray(ids);
//		List<Map<String,Object>> idList = JSONArray.pa();
//		System.out.println(idList.toString());
		Result result  = productService.batchDelete(ids);
		doResult(resp, result.isSuccess(), result.getCode(), result.getData(), result.getMessage());
	}
	
	
	/**
	 * Description:简单基础查询
	 * @param filterText
	 * @param page
	 * @param rows
	 * @param sort
	 * @param order
	 * @author around
	 * @date 2017年9月14日上午10:33:29
	 */
	@RequestMapping(value="/findBaseProduct",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public void findBaseProduct(HttpServletRequest req , HttpServletResponse resp,
			String filterText, Integer page, Integer rows, String sort, String order){
		try {
			PageUtils<ProductInfoVo> pageinfo = new PageUtils<ProductInfoVo>(page, rows, sort, order);
			Map<String,Object> condition = pageinfo.getCondition();
			condition.put("facId", getCurrentFactoryUser().getFacId());
			condition.put("filterText", filterText);
			
			productService.findBaseProductInfo(pageinfo);
			
			doResult(resp, true, StatusCode.FINDSUCCESS, pageinfo, ResultType.FIND_SUCCESS);
		}catch(Exception e){
			e.printStackTrace();
			doResult(resp, false, StatusCode.EXCEPTIONERROR, null, ResultType.FIND_FAULT);
		}
	}
	
	
	/**
	 * Description:处理厂商平台，商品详情的规格组合问题
	 * @param spec
	 * @return String
	 * @author around
	 * @date 2017年9月28日下午8:02:24
	 */
	private String splitSpec(String spec) {
		if (StringUtils.isEmpty(spec)) return "{}";
		else if ("{}".equals(spec)) return spec;
		//追加格式化部分
		spec = spec.replaceAll(":", "\":\"").replaceAll(",", "\",\"");
		return "{\"".concat(spec).concat("\"}");
	}
	
//	@RequestMapping(value="/selforOrder",method={RequestMethod.GET,RequestMethod.POST})
//	@ResponseBody
//	public void selectForOder(HttpServletRequest req , HttpServletResponse resp,Long skuId,Long ageId){
//		ProductSkuVo product = productService.selectForOder(skuId, ageId);
//		doResult(resp, true, product, "1111");
//	}
	
}

